let express = require("express");
let router = express.Router();
let { loginModel, roleModel, routesModel } = require("../model/model");
const jwt = require("jsonwebtoken");
const secret = 'secretKey'

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});

// 检查 Token 的中间件
function checkToken(req, res, next) {
  const token = req.headers['authorization'];
  if (!token) {
    return res.status(403).json({ message: 'Token is missing!' });
  }

  jwt.verify(token, secret, (err, decoded) => {
    if (err) {
      return res.status(403).json({ message: 'Token is invalid!' });
    }
    req.user = decoded;
    next();
  });
}

/* 登录 */
router.post("/login", async function (req, res, next) {
  let { username, password } = req.body;
  let user = await loginModel.findOne({ username });
  if (user) {
    if (user && user.password === password) {
      // let token = jwt.sign({ username }, secretKey, { expiresIn: 1000 * 3600 })
      let token = "Bearer" + " " + jwt.sign({ username: "admin" }, "secretKey", { expiresIn: "1d" });
      let refreshToken = "Bearer" + " " + jwt.sign({ username: "admin"}, secret);
      return res.send({
        code: 200,
        message: "登录成功",
        type: "success",
        data: user,
        token,
        refreshToken
      });
    } else if (user || user.password !== password) {
      return res.send({
        code: 201,
        message: "用户名或密码错误",
        type: "info",
      });
    }
  } else {
    return res.send({
      code: 400,
      type: "info",
      message: "无用户，请前往注册",
    });
  }
});

/* 注册 */
router.post("/register", async function (req, res, next) {
  let { username, password } = req.body;
  let user = await loginModel.findOne({ username });
  if (user) {
    return res.send({
      code: 400,
      type: "info",
      message: "用户已存在",
    });
  } else {
    await loginModel.create({ username, password });
    return res.send({
      code: 200,
      type: "success",
      message: "注册成功",
    });
  }
});

// 刷新 Token 的接口
router.post('/refresh', checkToken, (req, res) => {
  const user = req.body;
  const accessToken = jwt.sign({ username: user.username }, secret, { expiresIn: '30m' });
  res.json({ accessToken });
});

/* 创建路由 */
router.post("/routesCreate", async function (req, res, next) {
  await routesModel.create(req.body);
  res.send({
    code: 200,
    msg: "success",
  });
});

/* 路由列表 */
router.post("/routerDetail", async function (req, res, next) {
  const { role_id, pageSize, currentPage, _id } = req.body;
  let data = await routesModel.find().lean();
  let menulist = [];
  let total = await routesModel.find().count();
  if (_id) {
    data = await routesModel.find({ _id }).lean();
  } else if (role_id) {
    let [{ menu_id }] = await routesModel.find({ _id: role_id }).lean();
    menu_id.forEach((id) => {
      data.forEach((item) => {
        if (String(id) === String(item._id)) {
          menulist.push(item);
        }
      });
    });
  }
  menulist = data;

  if (pageSize && currentPage) {
    data = data.slice((currentPage - 1) * pageSize, currentPage * pageSize);
  } else if (!_id) {
    let obj = {};
    let list = [];
    menulist.forEach((item) => {
      obj[item._id] = item;
    });
    menulist.forEach((item) => {
      if (item.level === 1) {
        list.push(item);
      } else if (obj) {
        if (!obj[item.pid]["children"]) {
          obj[item.pid]["children"] = [];
        }
        obj[item.pid]["children"].push(item);
      }
    });
    data = list;
  }
  res.send({
    code: 200,
    type: "success",
    message: "获取成功",
    data,
    total,
    pageSize,
    currentPage,
  });
});
// 用户列表
router.post('/userList', async (req, res) => {
  let current = req.body.current || 1
  let pageSize = req.body.pageSize || 5
  let skip = (current - 1) * pageSize
  let data = []
  let total = 0
  let { _id, username } = req.body
  if (username || _id) {
    data = await loginModel.find({ ...req.body })
  } else {
    data = await loginModel.find().populate('rid').skip(skip).limit(pageSize)
  }

  total = await loginModel.find().count()
  res.send({
    code: 200,
    msg: '数据返回成功',
    pageData: data,
    total,
    current,
    pageSize
  })
})
// 用户添加
router.post("/userAdd", async function (req, res, next) {
  console.log(req.body)
  await loginModel.create(req.body)
  res.send({
    code: 200,
    type: "success",
    message: "添加成功",
  });
});
// 用户修改
router.post("/userEdit", async function (req, res, next) {
  console.log(req.body, 'ASDADS')
  let { _id } = req.body
  _id && await loginModel.updateOne({ _id }, req.body);
  res.send({
    code: 200,
    type: "success",
    message: "修改成功",
  });
});

router.post('/userDel', async function (req, res) {
  const { _id } = req.body
  await loginModel.deleteOne({ _id })
  res.send({
    code: 200,
    message: "删除成功",
    type: "success"
  })
})

// 角色添加
router.post("/roleCreate", async function (req, res, next) {
  let data = await roleModel.create(req.body);
  console.log(req.body)
  res.send({
    code: 200,
    type: "success",
    message: "添加成功",
    data,
  });
});
// 角色列表
router.post('/roleList', async (req, res) => {
  let page = req.body.page || 1
  let limit = req.body.limit || 5
  let data = []
  let total = 0
  let { name, state, _id } = req.body
  if (_id) {
    data = await roleModel.find({ _id })
  } else if (name && state) {
    data = await roleModel.find({ name, state })
  } else if (name) {
    data = await roleModel.find({ name })
  } else if (state === 0 || state === 1) {
    console.log(req.body, 'M<<<<<<<<<')
    data = await roleModel.find({ state })
  } else {
    data = await roleModel.find()
  }
  let pageData = data.slice((page - 1) * limit, page * limit)
  total = await roleModel.find().count()
  res.send({
    code: 200,
    msg: '数据返回成功',
    pageData,
    total,
    page,
    limit
  })
})
// 角色修改
router.post("/roleEdit", async function (req, res, next) {
  let { _id } = req.body
  await roleModel.updateOne({ _id }, req.body);
  res.send({
    code: 200,
    type: "success",
    message: "修改成功",
  });
});
// 角色删除
router.post("/roleDel", async function (req, res, next) {
  let { _id } = req.body
  await roleModel.deleteOne({ _id });
  res.send({
    code: 200,
    type: "success",
    message: "删除成功",
  });
});
// 不同的角色对应不同的权限
router.post("/diffRoleList", async (req, res) => {
  let { idx } = req.body;
  let data1 = await roleModel.find({ _id: idx }).populate("menu_id");
  let data = data1[0].menu_id;
  res.send({
    code: 200,
    msg: "数据获取成功",
    data,
    data1,
  });
});

module.exports = router;
